<?php

error_reporting(E_ALL | E_DEPRECATED);
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);

/**
 * For those unfortunate souls
 * who has magic_quotes enabled on their
 * server despite having php 5.3
 * this code will remove those
 * genocidal quotes added by magic_quotes
 */
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}


/**
 * Set all the multibyte
 * functions to use UTF-8
 * as internal encoding
 */
if (function_exists('mb_internal_encoding')) {
    mb_internal_encoding("UTF-8");
}

function exception_handler($e) {
    //echo 'Eeeeee '.$e->getMessage()."\n<br>";
    try {
        $err = StudyBuddy\Responder::makeErrorPage('<strong>Error:</strong> ' . StudyBuddy\Exception::formatException($e));
        $extra = (isset($_SERVER)) ? ' $_SERVER: ' . print_r($_SERVER, 1) : ' no extra';
        if (defined('STUDYBUDDY_DEVELOPER_EMAIL') && strlen(trim(constant('STUDYBUDDY_DEVELOPER_EMAIL'))) > 1) {
            @mail(STUDYBUDDY_DEVELOPER_EMAIL, 'ErrorHandle in inc.php', $err . $extra);
        }
        exit($err);
    } catch (\Exception $e) {
        echo 'Error in Exception handler: : ' . $e->getMessage() . ' line ' . $e->getLine() . $e->getTraceAsString();
    }
}

function debug($var, $obj=true) {
    echo '<pre>';
    if ($obj) {
        var_dump($var);
    } else {
        print_r($var);
    }
    echo '</pre>';
    die;
}

/**
 * if php NOT running as fastcgi
 * then we need to create a dummy function
 *
 */
if (!function_exists('fastcgi_finish_request')) {
    define('NO_FFR', true);

    function fastcgi_finish_request() {
        
    }

}

set_exception_handler('exception_handler');

define('STUDYBUDDY_PATH', realpath(dirname(__FILE__)));
$libDir = STUDYBUDDY_PATH . DIRECTORY_SEPARATOR . 'lib';
$StudyBuddyClasses = $libDir . DIRECTORY_SEPARATOR . 'StudyBuddy' . DIRECTORY_SEPARATOR;

require $StudyBuddyClasses . 'Interfaces' . DIRECTORY_SEPARATOR . 'All.php';
require $StudyBuddyClasses . 'Exception.php';
require $StudyBuddyClasses . 'Object.php';
require $StudyBuddyClasses . 'Responder.php';
require $StudyBuddyClasses . 'Mongo' . DIRECTORY_SEPARATOR . 'Collections.php';
require STUDYBUDDY_PATH . DIRECTORY_SEPARATOR . 'Mycollections.php';
require $StudyBuddyClasses . 'Ini.php';
require $StudyBuddyClasses . 'Log.php';
require $StudyBuddyClasses . 'Request.php';
require $StudyBuddyClasses . 'Mongo.php';
require $StudyBuddyClasses . 'MongoDoc.php'; // User extends it
require $StudyBuddyClasses . 'User.php'; // User is always used
require $StudyBuddyClasses . 'SplClassLoader.php';
require $StudyBuddyClasses . 'Registry.php';
require $StudyBuddyClasses . 'Template' . DIRECTORY_SEPARATOR . 'Template.php';

/**
 * Points.php is in non-standard directory,
 * in fact this file is not even included in distro
 * User must rename Points.php.dist to Points.php
 * That's why we should manually included it
 * because autoloader will not be able to find it.
 * This file only contains a few constants - it's cheap
 * to include it every time, and with APC cache it will
 * be cached.
 */
require STUDYBUDDY_PATH . DIRECTORY_SEPARATOR . 'Points.php';

/**
 * Custom error handle
 * the purpose of this is to catch
 * the catchable fatal error, intoduced in php 5.2.0
 * We use it with type hinting in class constructors
 * if the object passed to class constructor is not of the same type
 * as hinted, it generates a catchable fatal error.
 * The only way to catch it in the normal way is to set custom error handler
 * like this one, then re-throw exception and it will then be caught.
 *
 * This error handler also turns any php error into
 * a ErrorException
 *
 * So almost any error will be displayed in a better way on
 * the page, will be logged and email will be sent to admin.
 *
 *
 * @param integer $errno
 * @param string $errstr
 * @param string $errfile
 * @param integer $errline
 * @return true
 */
function StudyBuddyErrorHandler($errno, $errstr, $errfile, $errline) {
    $errLevel = error_reporting();
    //echo 'Booooooooo ' .$errLevel. ' '.$errno.' '. $errstr.' '. $errfile.' '. $errline.'<br>';

    if ($errno === E_RECOVERABLE_ERROR) {

        d($errfile . ' ' . $errline . ' ' . $errstr);
        $e = 'Caught catchable fatal error in file: %1$s<br>
		on line: %2$s
		<br><br>
		Error message: <br>
		%3$s<br>';

        $err = vsprintf($e, array($errfile, $errline, $errstr));

        throw new StudyBuddy\DevException($err);
    } else {

        if ($errLevel === 0) {

            return;
        }
        /**
         * If error level falls within our
         * error reporting mask, then throw an ErrorException
         */
        if ($errLevel & $errno) {

            throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
        }
    }

    return true;
}

$old_error_handler = set_error_handler("StudyBuddyErrorHandler");
// autoloader here
require 'autoload.php';

$oRegistry = \StudyBuddy\Registry::getInstance();

try {

    $oINI = $oRegistry->Ini;
    $dataDir = $oINI->STUDYBUDDY_DATA_DIR;
    $dataDir = rtrim($dataDir, '/');

    define('STUDYBUDDY_WWW_DIR', STUDYBUDDY_PATH . DIRECTORY_SEPARATOR . \StudyBuddy\WWW_DIR . DIRECTORY_SEPARATOR);
    //define('STUDYBUDDY_DEVELOPER_EMAIL', $oINI->EMAIL_DEVELOPER);
    define('STUDYBUDDY_SALT', $oINI->SALT);
    define('STUDYBUDDY_COOKIE_SALT', $oINI->COOKIE_SALT);
    define('STUDYBUDDY_DEFAULT_LANG', $oINI->DEFAULT_LANG);
    define('STUDYBUDDY_DEFAULT_LOCALE', $oINI->DEFAULT_LOCALE);
    define('STUDYBUDDY_TR_DIR', $oINI->TRANSLATIONS_DIR);
    define('STUDYBUDDY_COOKIE_DOMAIN', $oINI->COOKIE_DOMAIN);
    define('STUDYBUDDY_IMAGE_SITE', $oINI->IMAGE_SITE);

    define('STUDYBUDDY_AVATAR_IMG_SITE', $oINI->AVATAR_IMG_SITE);

    if (!empty($dataDir)) {
        define('STUDYBUDDY_DATA_DIR', $dataDir . DIRECTORY_SEPARATOR);
    } else {
        define('STUDYBUDDY_DATA_DIR', STUDYBUDDY_WWW_DIR . 'w' . DIRECTORY_SEPARATOR);
    }
} catch (StudyBuddy\IniException $e) {
    exit($e->getMessage());
}


/**
 * First thing is to set our timezone
 */
if (false === date_default_timezone_set($oINI->SERVER_TIMEZONE)) {
    throw new \StudyBuddy\DevException('Invalid name of  "SERVER_TIMEZONE" in !config.ini constant. The list of valid timezone names can be found here: http://us.php.net/manual/en/timezones.php');
}

/**
 * The DEBUG is automatically enabled for
 * users whose ip addresses are added to
 * MY_IP section of config.inc
 * or if script is run from console
 */
$myIP = \StudyBuddy\Request::getIP();

$aMyIPs = $oINI->offsetGet('MY_IP');
$debug = $oINI->DEBUG;

if ($debug || isset($aMyIPs[$myIP]) || defined('SPECIAL_LOG_FILE')) {
//    define('STUDYBUDDY_DEBUG', true);
//    error_reporting(E_ALL | E_DEPRECATED);
//    ini_set('display_errors', 1);
//    ini_set('display_startup_errors', 1);
//    ini_set('warn_plus_overloading', 1);
    
    define('STUDYBUDDY_DEBUG', false);
    error_reporting(E_ALL ^ E_WARNING);
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    ini_set('warn_plus_overloading', 0);
} else {
    define('STUDYBUDDY_DEBUG', false);
    error_reporting(E_ALL ^ E_WARNING);
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
    ini_set('warn_plus_overloading', 0);
}

define('LOG_FILE_PATH', $oINI->LOG_FILE_PATH);

/**
 * Empty the log file if
 * necessary
 */
/**
 * LOG_PER_SCRIPT
 * will return string '1' for true
 * or empty string for false
 */
if ((true === STUDYBUDDY_DEBUG) && ('' !== LOG_FILE_PATH) && (true === (bool) $oINI->LOG_PER_SCRIPT) && !\StudyBuddy\Request::isAjax()) {

    file_put_contents(LOG_FILE_PATH, PHP_SAPI . ' ' . print_r($_SERVER, 1), LOCK_EX);
}

/**
 * Shortcuts to log debug and log error
 * MUST BE CALLED after DEBUG MODE and LOG_FILE_PATH
 * has been defined
 */
function d($message) {
    if (defined('STUDYBUDDY_DEBUG') && true === STUDYBUDDY_DEBUG) {
        \StudyBuddy\Log::d($message, 2);
    }
}

function e($message) {
    \StudyBuddy\Log::e($message, 2);
}

/**
 * Must be called here AFTER autoloaders have
 * been registered because it relies on autoloaders
 * to find observer classes
 */
$oRegistry->registerObservers();

